package org.september.pisces.filestore.service.hik;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
public class RequestHandler {


    public String sendRequest(HttpMethodBase httpMethodBase) {
        // 输入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        // 创建httpClient实例
        HttpClient httpClient = new HttpClient();

        // 先获取连接管理器对象，再获取参数对象,再进行参数的赋值

        try {
            // 执行请求
            int statusCode = httpClient.executeMethod(httpMethodBase);
            // 判断返回码
            if (statusCode != HttpStatus.SC_OK) {
                log.error("请求海康存储失败;statusLine:{},错误body:{}",httpMethodBase.getStatusLine(), httpMethodBase.getResponseBodyAsString());

            } else {
                // 通过getMethod实例，获取远程的一个输入流
                is = httpMethodBase.getResponseBodyAsStream();
                // 包装输入流
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                // 读取封装的输入流
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp).append("\r\n");
                }

                result = sbf.toString();

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 释放连接
            httpMethodBase.releaseConnection();
        }
        return result;
    }


    public InputStream sendRequestReturnStream(HttpMethodBase httpMethodBase) {
        // 输入流
        InputStream is = null;
        try {
            HttpClient httpClient = new HttpClient();
            int statusCode = httpClient.executeMethod(httpMethodBase);
            if (statusCode != HttpStatus.SC_OK) {
                log.error("海康存储失败;statusLine:{}",httpMethodBase.getStatusLine());
                log.error("错误body:{}",httpMethodBase.getResponseBodyAsString());
            } else {
                is = httpMethodBase.getResponseBodyAsStream();
            }
        } catch (IOException e) {
            log.error("sendRequestReturnStream",e);
        }
        return is;
    }


}
